package com.blog.cmrpersonalblog.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.cmrpersonalblog.entity.SysPermission;
import com.blog.cmrpersonalblog.mapper.SysPermissionMapper;
import com.blog.cmrpersonalblog.service.SysPermissionService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 系统权限服务实现类
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {

    @Override
    public SysPermission getPermissionByPermKey(String permKey) {
        return baseMapper.selectPermissionByPermKey(permKey);
    }

    @Override
    public List<SysPermission> getPermissionsByRoleId(Long roleId) {
        return baseMapper.selectPermissionsByRoleId(roleId);
    }

    @Override
    public List<SysPermission> getPermissionsByUserId(Long userId) {
        return baseMapper.selectPermissionsByUserId(userId);
    }

    @Override
    public List<SysPermission> getAllPermissions() {
        return baseMapper.selectAllPermissions();
    }

    @Override
    public boolean canDeletePermission(Long permId) {
        int roleCount = baseMapper.countRolesByPermId(permId);
        return roleCount == 0;
    }

    @Override
    public List<SysPermission> getPermissionsByPermKeys(List<String> permKeys) {
        if (permKeys == null || permKeys.isEmpty()) {
            return List.of();
        }
        return baseMapper.selectPermissionsByPermKeys(permKeys);
    }

    @Override
    public boolean hasPermission(Long userId, String permKey) {
        List<SysPermission> permissions = getPermissionsByUserId(userId);
        return permissions.stream()
                .anyMatch(permission -> permission.getPermKey().equals(permKey));
    }

    @Override
    public boolean hasAnyPermission(Long userId, List<String> permKeys) {
        if (permKeys == null || permKeys.isEmpty()) {
            return false;
        }
        
        List<SysPermission> userPermissions = getPermissionsByUserId(userId);
        List<String> userPermKeys = userPermissions.stream()
                .map(SysPermission::getPermKey)
                .toList();
        
        return permKeys.stream().anyMatch(userPermKeys::contains);
    }
}
